<?php
namespace PsiFramework\Applications\AlloMediaAdmin\Classes\Actions;

import("Classes.Actions.AbstractAction");
import("Classes.Util.HTTP.AuthenticationManager");
import("Classes.Factory.DAOFactory");

use \PsiFramework\Classes\Actions\AbstractAction;
use \PsiFramework\Classes\Util\Parameters\Action\ActionParameters;
use \PsiFramework\Classes\Factory\DAOFactory;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Classe d'action de l'index
 *
 * @package Actions.Pages
 */
class AlloMediaUserSave extends AbstractAction
{

    public function __construct(ActionParameters $actionParameters)
    {
        parent::__construct($actionParameters);
    }

    /**
     * The main function of the method which is called every time
     * an action is created by the front controller.
     *
     */
    public function execute()
    {
        parent::execute();

        $error = null ;
        $message = null ;
        $pwd = $this->_request->getParameter('old_password');

        if ($pwd == md5($this->_request->getParameter('confirm_old_password'))
        ) {

            $id = $this->_request->getParameter('id');

            $userDao = DAOFactory::getDAO('User');
            $user = $userDao->retrieveByPk($id);
            $this->_response->setAttribute("user", $user);

            if (!is_null($user)) {
                $user->setLogin($this->_request->getParameter('login'));
                $user->setEmail($this->_request->getParameter('email'));
                $user->setPassword($pwd);

                $newPwd = $this->_request->getParameter('new_password');
                if (!isNullOrEmptyString($newPwd)) {
                    if ($newPwd  == $this->_request->getParameter('confirm_new_password')
                    ) {
                        $user->setPassword(md5($newPwd));
                    } else {
                        $error
                            = "Le nouveau mot de passe entré est ".
                            "différent du mot de passe confirmé." ;
                    }
                }

                $ok = $userDao->save($user);

                if ($ok) {
                    $message = "Informations mises à jour." ;
                } else {
                    $error = "Erreur lors de l'insertion en base !" ;
                }

            } else {
                $error = "Impossible de récupérer les paramètres en base." ;
            }

        } else {
            $error = "L'ancien mot de passe entré n'est pas valide." ;
        }

        $this->_response->setAttribute("error", $error);
        $this->_response->setAttribute("message", $message);

        $this->findForward('success');
    }
}
